package top.mengchaob.fileserver.netty.busAtomHandler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.mengchaob.fileserver.netty.bean.ResultBeanNetty;

import static io.netty.buffer.Unpooled.copiedBuffer;

/**
 * @title：
 * @author: mengchaob
 * @date: 2021年05月19日 16:30
 * @description:
 */
public class ResponseHandler extends SimpleChannelInboundHandler<HttpObject> {
    private static final Logger logger = LoggerFactory.getLogger(ResponseHandler.class);
    private HttpRequest request;
    @Override
    public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
            this.request = (HttpRequest) msg;
            this.response(ctx);
    }

    private void response(ChannelHandlerContext ctx){
        AttributeKey<ResultBeanNetty> reusltBean = AttributeKey.valueOf("resultBean");
        ResultBeanNetty resultBean = ctx.channel().attr(reusltBean).get();
        resultBean.setErrcode("0");
        resultBean.setMsg("保存成功！");
        ByteBuf buf = copiedBuffer(resultBean.toString(), CharsetUtil.UTF_8);
        // Build the response object.
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN,"*");
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true");
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "Origin, X-Requested-With, Content-Type, Accept");
        // Decide whether to close the connection or not.
        boolean keepAlive = HttpUtil.isKeepAlive(request);
        if (!keepAlive) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        } else if (request.protocolVersion().equals(HttpVersion.HTTP_1_0)) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }

        // Write the response.
        ChannelFuture future = ctx.channel().writeAndFlush(response);
        // Close the connection after the write operation is done if necessary.
        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.pipeline().remove("responseHandler");
        logger.debug("exceptionCaught删除ResponseHandler");
        this.response(ctx);
    }

}
